<style lang="less">
  @import '../styles/common.less';
  @import '../tables/components/table.less';
</style>

<template>
  <div class="div-relative">
    <Row :gutter="10">
      <Card>
        <div class="table-head" v-show="selectionArr.length == 0">
          <div class="left">
            <Select v-model="typeSelectid" :transfer="true" @on-change="onChangeTypeSelect">
              <Option v-for="item in typeSelect" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </div>
          <div class="left">
            <Input v-model="search_title" size="default" placeholder="标题"/>
          </div>
          <div class="left-btn">
            <Button type="text" icon="ios-search" @click="searchFun()">搜索</Button>
          </div>
          <Button type="text" icon="ios-cloud-download" class="Button" @click="ExportData()" v-if="data.length > 0">导出
          </Button>
        </div>
        <div class="table-head" v-show="selectionArr.length > 0">
          <div class="left-nums">选中 {{selectionArr.length}} 条 / 共 {{data.length}} 条</div>
          <div class="left-btn">
            <Button type="error" class="Button" @click="remove()">删除</Button>
          </div>
          <div class="left-btn">
            <Button type="primary" class="Button" @click="ExportData()">导出</Button>
          </div>
          <Button type="text" class="Button" @click="hideNums()">取消</Button>
        </div>
        <Row class="margin-top-10">
          <Table stripe border :columns="columns" :data="data" @on-row-click="onRowData"
                 @on-selection-change="selectionChange" ref="selectionTable" @on-sort-change="onSortChange"></Table>
        </Row>
        <div style="margin: 10px;overflow: hidden;height: 36px;">
          <div style="float: right;">
            <Page :total="total" :current="page" @on-change="changePage" show-elevator></Page>
          </div>
        </div>
      </Card>
      <!--详情-->
      <Modal v-model="showCurrentTableData" :width="600" :mask-closable="false" :closable="false"
             class-name="vertical-center-modal" class="Modal-Detail-div">
        <h3 slot="header" style="color:#2D8CF0">{{dataDetail.title}}详情</h3>
        <Form label-position="top">
          <FormItem label="昵称" v-if="dataDetail.nick_name">
            <div class="dataDetail-div display-flex">
              <user-avatar
                :user_id="dataDetail.id"
                :user_name="dataDetail.anonymous == true ? '匿名用户' : dataDetail.nick_name"
                :user_img="dataDetail.anonymous == true ? '' : dataDetail.avatar"
                :fun="false"
              >
              </user-avatar>
            </div>
          </FormItem>
          <FormItem label="标题" v-if="dataDetail.title">
            <div class="dataDetail-div" v-text="dataDetail.title"></div>
          </FormItem>
          <FormItem label="状态" v-if="dataDetail.status">
            <div class="dataDetail-div" v-text="dataDetail.status"></div>
          </FormItem>
          <FormItem label="时间" v-if="dataDetail.create_time">
            <div class="dataDetail-div" v-text="dataDetail.create_time"></div>
          </FormItem>
          <FormItem label="是否匿名">
            <div class="dataDetail-div" v-text="dataDetail.anonymous==true ? '是' : '否'"></div>
          </FormItem>
          <FormItem label="内容" v-if="dataDetail.content">
            <div class="dataDetail-div" v-text="dataDetail.content"></div>
          </FormItem>
          <FormItem label="" v-if="dataDetail.image && dataDetail.image.length > 0">
            <div class="dataDetail-div">
              <img v-for="el in dataDetail.image" :src="el.url" class="img">
            </div>
          </FormItem>
          <FormItem label="任务负责人" v-if="dataDetail.task_chargeName && dataDetail.task_chargeName!=''">
            <div class="dataDetail-div" v-text="dataDetail.task_chargeName"></div>
          </FormItem>
          <FormItem label="任务状态" v-if="dataDetail.task_status && dataDetail.task_status!=''">
            <div class="dataDetail-div" v-text="dataDetail.task_status"></div>
          </FormItem>
          <FormItem label="阅读情况">
            <div class="dataDetail-div padding-0">
              <Table stripe border :columns="readList_columns" :data="readList"></Table>
              <div class="readList_page_div text-align-center" v-if="readList_total > 0">
                <Page :total="readList_total" :current="readList_page" size="small" @on-change="readList_changePage"
                      show-elevator></Page>
              </div>
            </div>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="asyncOK">取消</Button>
          <Button type="info" @click="toTask()" v-if="!(dataDetail.task && dataDetail.task.id)">转为任务</Button>
        </div>
      </Modal>
      <!--编辑-->
      <Modal v-model="addCurrentTableData" :width="600" :mask-closable="false" :closable="false"
             class-name="vertical-center-modal" class="Modal-Detail-div">
        <h3 slot="header" style="color:#2D8CF0">编辑</h3>
        <Form label-position="top">
          <FormItem label="标题">
            <Input v-model="addData.title" placeholder="标题"></Input>
          </FormItem>
          <FormItem label="内容">
            <Input v-model="addData.content" type="textarea" class="textarea_resize"
                   :autosize="{minRows: 3}" placeholder="内容"></Input>
          </FormItem>
          <FormItem label="是否匿名">
            <i-switch v-model="addData.anonymous" size="large">
              <span slot="open">是</span>
              <span slot="close">否</span>
            </i-switch>
          </FormItem>
          <FormItem label="图片">
            <div class="dataDetail-div chooseUser accessory">
              <img v-for="el in addData.accessory" :src="el.url" class="img">
              <Upload
                :before-upload="handleUpload" action="" accept="image/*" :format="format"
                :multiple="true">
                <Button icon="ios-cloud-upload-outline">选择文件</Button>
              </Upload>
            </div>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="hideAddModal">取消</Button>
          <Button type="primary" :loading="saveLoading" @click="save()">确定</Button>
        </div>
      </Modal>
    </Row>
    <spin-page :showSpin="showSpin"></spin-page>
  </div>
</template>

<script>
  import Cookies from 'js-cookie';
  import Util from '../../libs/util';
  import Utils from '../../libs/mod.utils';
  import String from '../../libs/mod.string';
  import Modal from '../../libs/mod.Modal';
  import userAvatar from '../components/user-avatar.vue';
  import spinPage from '../components/spin-page.vue';
  export default {
    components: {
      userAvatar,
      spinPage
    },
    data () {
      return {
        total: 0,
        page: 1,
        size: 10,
        order_by: [],
        readList_total: 0,
        readList_page: 1,
        id: '',
        typeSelectid: 'all',
        typeSelect: [
          {
            id: 'all',
            name: '全部',
          },
          {
            id: 'wish',
            name: '心愿',
          },
          {
            id: 'suggest',
            name: '建议',
          },
        ],
        searchConName: '',
        searchConTel: '',
        showCurrentTableData: false,
        loading: true,
        showCurrentColumns: [],
        editInlineAndCellData: [],
        columns: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            key: 'nick_name',
            title: '昵称',
            align: 'center',
            sortable: 'custom',
          },
          {
            key: 'title',
            title: '标题',
            align: 'center',
            sortable: 'custom',
          },
          {
            key: 'type',
            title: '类型',
            align: 'center',
            sortable: 'custom',
            render: (h, params) => {
              var type = params.row.type;
              if (type == 'wish') {
                type = '心愿';
              } else if (type == 'suggest') {
                type = '建议';
              }
              return h('div', [
                h('span', type)
              ]);
            }
          },
          {
            key: 'status',
            title: '状态',
            align: 'center',
            sortable: 'custom',
          },
          {
            key: 'anonymous',
            title: '是否匿名',
            align: 'center',
            sortable: 'custom',
            width: 120,
            render: (h, params) => {
              return h('div', [
                h('span', params.row.anonymous == true ? '是' : '否')
              ]);
            }
          },
          {
            key: 'create_time',
            title: '时间',
            align: 'center',
            sortable: 'custom',
            width: 200
          },
        ],
        data: [],
        dataDetail: {},
        readList: [],
        readList_columns: [
          {
            key: 'name',
            title: '姓名',
          },
          {
            key: 'status',
            title: '阅读状态',
            render: (h, params) => {
              return h('div', [
                h('span', params.row.status == true ? '已读' : '未读')
              ]);
            }
          },
          {
            key: 'read_time',
            title: '阅读时间',
          },
        ],
        initTable: [],
        format: Util.constant.format,
        addCurrentTableData: false,
        saveLoading: false,
        ajaxType: 'add',
        addData: {
          title: '',
          content: '',
          anonymous: false,
          accessory: [],
        },
        selectionArr: [],
        search_title: '',
        showSpin: false,//加载中
      };
    },
    created: function () {
      var _this = this;
      // 收藏夹跳转过来的
      var collection_list_str = sessionStorage.getItem('collection_list');
      if (collection_list_str && collection_list_str != '') {
        var collection_list_obj = Util.toJson(collection_list_str);
        var id = collection_list_obj.id || '';
        var type = collection_list_obj.type || '';
        sessionStorage.removeItem('collection_list');
      }
    },
    mounted () {
      this.getData();
    },
    methods: {
      // 搜索
      searchFun: function () {
        var _this = this;
        _this.page = 1;
        _this.getData();
      },
      onChangeTypeSelect: function (val) {
        var _this = this;
        _this.typeSelectid = val;
        _this.page = 1;
        _this.getData();
      },
      // 取消列表选中
      hideNums: function () {
        var _this = this;
        this.$refs.selectionTable.selectAll(false);
        _this.selectionArr = [];
      },
      // 排序
      onSortChange: function (data) {
        var _this = this;
        var column = data.column;
        var key = data.key;
        switch (key) {
          case 'status' :
            key = 'task.status';
            break;
        }
        var order = data.order;
        if (order == 'asc' || order == 'desc') {
          var orderObj = {
            field: key,
            sort: order,
          };
          _this.order_by = [orderObj];
          _this.getData();
        } else {
          _this.order_by = [];
          _this.getData();
        }
      },
      getData () {
        var _this = this;
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          type: _this.typeSelectid == 'all' ? '' : _this.typeSelectid,
          page: _this.page,
          size: _this.size,
          title: _this.search_title.trim(),
          order_by: _this.order_by,
        };
        var params = {
          url: '/wish/list',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.showSpin = true;
        function _successFun(res) {
          _this.showSpin = false;
          if (res.result == 0) {
            var _data = res.data || [];
            _this.total = res.rows;
            _this.data = _data;
            _this.hideNums();
          } else {
            _this.$Message.destroy();
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      handleSearch () {
        var _this = this;
        _this.page = 1;
        var searchConName = _this.searchConName;
      },
      changePage (page) {
        var _this = this;
        console.log('page', page);
        _this.page = page;
        _this.getData();
      },
      onRowData: function (data, index) {
        var _this = this;
        _this.readUpdate(data);
      },
      show: function (data) {
        var _this = this;
        var id = data.id;
        _this.id = id;

        var data = {
          id: _this.id,
        };
        var params = {
          url: '/wish/query',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.showSpin = true;
        function _successFun(res) {
          _this.showSpin = false;
          if (res.result == 0) {
            var _data = res.data || [];
            var task = _data.task;
            var charge = task.charge || {};
            var task_chargeName = charge.name ? charge.name : '';
            var status = task.status || '';
            switch (status) {
              case "not-begun" :
                status = '未完成';
                break;
              case "started" :
                status = '已开始';
                break;
              case "delayed" :
                status = '已延期';
                break;
              case "finished" :
                status = '已完成';
                break;
              case "archived" :
                status = '已归档';
                break;
              case "ahead-finished" :
                status = '提前完成了';
                break;
              case "overtime-finished" :
                status = '延期完成了';
                break;
              default:
                break;
            }
            _data.task_chargeName = task_chargeName;
            _data.task_status = status;
            _this.dataDetail = _data;
            _this.showCurrentTableData = true;
          } else {
            _this.$Message.destroy();
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      asyncOK: function () {
        var _this = this;
        _this.showCurrentTableData = false;
      },
      // 已读未读,分页条
      readList_changePage: function (page) {
        var _this = this;
        _this.readList_page = page;
        _this.getReadList();
      },
      // 更新已读
      readUpdate: function (Detail_data) {
        var _this = this;
        var id = Detail_data.id;
        _this.id = id;
        var data = {
          tid: _this.id,
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          type: 'wish',
        };
        var params = {
          url: '/read/status/update',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {

          } else {

          }
          _this.show(Detail_data);
          _this.readList_page = 1;
          _this.getReadList();
        }
      },
      // 查看已读列表
      getReadList: function () {
        var _this = this;
        var data = {
          tid: _this.id,
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          type: 'wish',
          page: _this.readList_page,
          size: _this.size,
        };
        var params = {
          url: '/read/status/list',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            _this.readList_total = res.rows || 0;
            _this.readList = res.data ? res.data : [];
          } else {
            _this.$Message.destroy();
            _this.$Message.error('查询已读人员列表失败!');
          }
        }
      },
      // 转到任务
      toTask: function () {
        var _this = this;
        var id = _this.id;
        var title = _this.dataDetail.title;
        var content = _this.dataDetail.content;
        var data = {
          pid: id,
          title: title,
          content: content,
        };
        sessionStorage.setItem('wish_data', Util.toStr(data));
        Util.openNewPage(_this, 'task_index');
        _this.$router.push({
          name: 'task_index'
        });

        _this.addCurrentTableData = false;
        _this.showCurrentTableData = false;
      },
      // 选中文件
      handleUpload: function (file) {
        var _this = this;
        _this.UploadFile(file);
        return false;
      },
      // 上传文件
      UploadFile: function (file) {
        var _this = this;
        var name = file.name;
        var arr = name.split('.');
        var type = arr[arr.length - 1];
        if (!(Util.constant.format.indexOf(type) > -1)) {
          _this.$Message.destroy();
          _this.$Message.error('请上传图片!');
          return false;
        }
        var formData = new FormData();
        formData.append("file", file);
        formData.append("type", "image");
        var params = {
          url: '/attach/addFile',
          type: Util.method.post,
          data: formData,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var data = res.data;
            var id = data.id;
            var name = data.name;
            var url = data.url;
            var obj = {
              id: id,
              name: name,
              url: url,
            };
            _this.addData.accessory.push(obj);
          } else {
            _this.$Message.destroy();
            _this.$Message.error('上传失败!');
          }
        }
      },
      // 删除附件
      delAccessory: function (el) {
        var _this = this;
        var id = el.id;
        var accessory = _this.addData.accessory;
        for (var k in accessory) {
          if (!accessory[k]) {
            continue;
          }
          if (id == accessory[k].id) {
            var del = accessory.splice(k, 1);
            break;
          }
        }
        _this.addData.accessory = accessory;
      },
      // 列表多选 选中数据
      selectionChange: function (selection) {
        var _this = this;
        _this.selectionArr = selection;
      },
      // 隐藏编辑页面
      hideAddModal: function () {
        var _this = this;
        _this.addCurrentTableData = false;
      },
      // 显示添加界面
      add: function () {
        var _this = this;
        _this.ajaxType = 'add';
        _this.addCurrentTableData = true;
      },
      // 保存数据
      save: function () {
        var _this = this;
        var title = _this.addData.title;
        var content = _this.addData.content;
        var anonymous = _this.addData.anonymous;
        var accessory = _this.addData.accessory;
        if (!(title && title != '')) {
          _this.$Message.destroy();
          _this.$Message.error('请填写标题!');
          return false;
        }
        if (!(content && content != '')) {
          _this.$Message.destroy();
          _this.$Message.error('请填写内容!');
          return false;
        }
        var images = [];
        for (var k in accessory) {
          if (!accessory[k]) {
            continue;
          }
          images.push(accessory[k].id);
        }
        var data = {
          id: _this.id,
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          type: 'wish',
          title: title,
          anonymous: anonymous,
          content: content,
          images: images,
        };
        var url = '/feedback/add';
        if (_this.ajaxType == 'update') {
          url = '/feedback/update';
        }
        var params = {
          url: url,
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.page = 1;
            _this.getData();
            _this.addCurrentTableData = false;
            _this.addData.content = '';
            _this.addData.anonymous = false;
            _this.addData.accessory = [];
          } else {
            _this.$Message.destroy();
            _this.$Message.error('保存信息失败!');
          }
        }

      },
      // 显示修改界面
      update: function (data, index) {
        var _this = this;
        _this.ajaxType = 'update';
        var id = data.id;
        _this.id = id;
        var data = {
          id: _this.id,
        };
        var params = {
          url: '/feedback/query',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.addData.content = _data.content;
            _this.addData.anonymous = _data.anonymous;
            _this.addData.accessory = _data.image;
            _this.addCurrentTableData = true;
          } else {
            _this.$Message.destroy();
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      // 删除
      remove: function () {
        var _this = this;
        var selectionArr = _this.selectionArr;
        if (selectionArr.length == 0) {
          _this.$Message.destroy();
          _this.$Message.error('请选择要删除的数据!');
          return false;
        }
        var selectionIds = [];
        for (var k in selectionArr) {
          if (!selectionArr[k]) {
            continue;
          }
          var id = selectionArr[k].id;
          selectionIds.push(id);
        }
        Modal.confirm(_this, {content: '确定删除选中的信息？'}, function () {
          var data = {
            id: selectionIds,
          };
          var params = {
            url: '/feedback/deleteMultiple',
            type: Util.method.post,
            data: data,
            success: _successFun
          };
          Util.ajax(_this, params);
          function _successFun(res) {
            if (res.result == 0) {
              _this.page = 1;
              _this.getData();
            } else {
              _this.$Message.destroy();
              _this.$Message.error('删除信息失败!');
            }
          }
        }, function () {
        });
      },
      // 导出
      ExportData: function () {
        var _this = this;
        var fields = [
          {
            field: 'nick_name',
            title: '昵称',
            type: 'varchar',
            order: 1,
          },
          {
            field: 'title',
            title: '标题',
            type: 'varchar',
            order: 2,
          },
          {
            field: 'type',
            title: '类型',
            type: 'varchar',
            order: 3,
          },
          {
            field: 'anonymous',
            title: '是否匿名',
            type: 'varchar',
            order: 4,
          },
          {
            field: 'pure_text',
            title: '内容',
            type: 'varchar',
            order: 5,
          },
          {
            field: 'create_time',
            title: '时间',
            type: 'datetime',
            order: 6,
          },
        ];
        var selectionArr = _this.selectionArr;
        if (selectionArr.length == 0) {
          selectionArr = _this.data;
        }
        var selectionIds = [];
        for (var k in selectionArr) {
          if (!selectionArr[k]) {
            continue;
          }
          var id = selectionArr[k].id;
          selectionIds.push(id);
        }

        var fieldsStr = Util.toStr(fields);
        var data = {};
        if (selectionIds.length > 0 && selectionIds.length == _this.data.length) { // 全选了
          Modal.confirm(_this, {content: '确定要导出全部信息？'}, function () {
            selectionIds = [];
            data = {
              uid: Util.toJson(localStorage.getItem('userInfo')).id,
              type: 'feedback-wechat',
              fields: fieldsStr,
            };
            _getAjax();
          }, function () {
            data = {
              uid: Util.toJson(localStorage.getItem('userInfo')).id,
              type: 'feedback-wechat',
              fields: fieldsStr,
              ids: selectionIds,
            };
            _getAjax();
          });
        } else {
          data = {
            uid: Util.toJson(localStorage.getItem('userInfo')).id,
            type: 'feedback-wechat',
            fields: fieldsStr,
            ids: selectionIds,
          };
          _getAjax();
        }
        function _getAjax() {
          var params = {
            url: '/attach/db2excle',
            type: Util.method.post,
            data: data,
            success: _successFun
          };
          Util.ajax(_this, params);
          _this.showSpin = true;
        }

        function _successFun(res) {
          _this.showSpin = false;
          if (res.result == 0) {
            var url = res.data;
            var date = Utils.dateToDateString(new Date());
            Utils.DownloadFile(url, '导出微心愿_' + date + '.xlsx');
          } else {
            _this.$Message.destroy();
            _this.$Message.error('导出信息失败!');
          }
        }
      },
    }
  };
</script>
